import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi } from '@/services/api'
import type { LoginDto, LoginResponseDto, ApiResult } from '@/types/auth'

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string>(localStorage.getItem('token') || '')
  const userInfo = ref<LoginResponseDto | null>(null)
  const isAuthenticated = ref<boolean>(!!localStorage.getItem('token'))

  const login = async (loginData: LoginDto): Promise<ApiResult<LoginResponseDto>> => {
    try {
      const result = await loginApi(loginData)
      
      // 检查result是否为空
      if (!result) {
        return {
          msg: '登录失败，请重试',
          code: 500,
          data: {} as LoginResponseDto
        }
      }
      
      if (result.code === 200 && result.data) {
        token.value = result.data.token
        userInfo.value = result.data
        isAuthenticated.value = true
        
        // 存储到localStorage
        localStorage.setItem('token', result.data.token)
        localStorage.setItem('userInfo', JSON.stringify(result.data))
        
        // 更新axios默认headers
        const updateAuthToken = (window as any).updateAuthToken
        if (updateAuthToken) {
          updateAuthToken(result.data.token)
        }
        
        return result
      }
      
      return result
    } catch (error) {
      console.info(import.meta.env.VITE_APP_API_URL)
      console.error('登录失败:', error)
      return {
        msg: '登录失败，请重试',
        code: 500,
        data: {} as LoginResponseDto
      }
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
    isAuthenticated.value = false
    
    // 清除localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    
    // 清除axios默认headers
    const updateAuthToken = (window as any).updateAuthToken
    if (updateAuthToken) {
      updateAuthToken('')
    }
  }

  const checkAuth = () => {
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    
    if (storedToken && storedUserInfo) {
      try {
        token.value = storedToken
        userInfo.value = JSON.parse(storedUserInfo)
        isAuthenticated.value = true
        
        // 更新axios默认headers
        const updateAuthToken = (window as any).updateAuthToken
        if (updateAuthToken) {
          updateAuthToken(storedToken)
        }
      } catch (error) {
        console.error('解析用户信息失败:', error)
        logout()
      }
    } else {
      logout()
    }
  }

  checkAuth()

  return {
    token,
    userInfo,
    isAuthenticated,
    login,
    logout,
    checkAuth
  }
}) 